#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
#include <arpa/inet.h>
#define PORT 8080
int main() {
    int sock = 0;
    struct sockaddr_in serv_addr;
    char buffer[1024] = {0};
    // 创建客户端套接字
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket failed");
        return -1;
    }
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // 将IP地址转化为网络字节顺序
    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        perror("Invalid address/ Address not supported");
        return -1;
    }

    // 连接服务器
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("connect failed");
        return -1;
    }

    std::cout << "Connected to server!" << std::endl;

    // 向服务器发送请求
    const char *message = "Hello from client!";
    send(sock, message, strlen(message), 0);
    std::cout << "Request sent to server: " << message << std::endl;

    // 接收服务器的响应
    int valread = read(sock, buffer, 1024);
    std::cout << "Response from server: " << buffer << std::endl;

    // 关闭套接字
    close(sock);

    return 0;
}
